<template>
	<view>
		<view class="box">
			<view class="boxTitle">
				请填写您的信息
			</view>
			<u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth="100">
				<u-form-item :required='true' label="店铺名称" prop="info.storeName" borderBottom ref="item1">
					<u--input :disabled="model1.info.processStatus==0" v-model="model1.info.storeName" border="none"></u--input>
				</u-form-item>
				<u-form-item :required='true' label="公司名称" prop="info.comName" borderBottom ref="item1">
					<u--input :disabled="model1.info.processStatus==0" v-model="model1.info.comName" border="none"></u--input>
				</u-form-item>
				<u-form-item :required='true' label="申请人姓名" prop="info.name" borderBottom ref="item1">
					<u--input :disabled="model1.info.processStatus==0" v-model="model1.info.name" border="none"></u--input>
				</u-form-item>
				<u-form-item :required='true' label="申请人电话" prop="info.phone" borderBottom ref="item1">
					<u--input :disabled="model1.info.processStatus==0" type="number" v-model="model1.info.phone" border="none"></u--input>
				</u-form-item>
				<u-form-item label="区/县" prop="info.county" borderBottom ref="item1"
					@click="!model1.info.processStatus==0?show=true:''">
					<view class="countBox1" v-if="!model1.info.county">
						请选择区/县
					</view>
					<view class="countBox2" v-else>
						{{countNmae}}
					</view>
				</u-form-item>
				<u-form-item :required='true' label="店铺地址" prop="info.storeAddress" borderBottom ref="item1">
					<u--input :disabled="model1.info.processStatus==0" v-model="model1.info.storeAddress" border="none"></u--input>
				</u-form-item>
				<u-form-item :required='true' label="社会信用代码" prop="info.creditCode" borderBottom ref="item1">
					<u--input :disabled="model1.info.processStatus==0" v-model="model1.info.creditCode" border="none"></u--input>
				</u-form-item>
				<!-- <u-form-item :required='true' label="店铺内桌数" prop="info.deskNum" borderBottom ref="item1">
					<u--input type="number" v-model="model1.info.deskNum" border="none"></u--input>
				</u-form-item> -->
				<u-form-item :required='true' label="是否省外商家" prop="info.isOutsideProvince" borderBottom ref="item1">
					<view class="radioBox">
						<u-radio-group :disabled="model1.info.processStatus==0" v-model="model1.info.isOutsideProvince" placement="row">
							<u-radio :customStyle="{marginLeft: '20px'}" v-for="(item, index) in radiolist1"
								:key="index" :label="item.name" :name="item.value" @change="groupChange">
							</u-radio>
						</u-radio-group>
					</view>
				</u-form-item>
				<u-form-item :required='true' :borderBottom='false' label="营业执照" prop="info.businessLicenseUrl"
					ref="item1">
				</u-form-item>
				<view class="imgBox">
					<uni-file-picker
						v-model="model1.info.businessLicenseFile"
						:disabled="model1.info.processStatus==0"
						:del-icon="!model1.info.processStatus==0"
						@select="(e) => select(e, 'business')"
						sizeType="['compressed']"
						return-type="object">
					</uni-file-picker>
				</view>
				<view class="held">

				</view>
				<u-form-item :required='true' label="商铺门牌照" prop="info.facadeUrl" :borderBottom='false' ref="item1">
				</u-form-item>
				<view class="imgBox">
					<uni-file-picker 
						v-model="model1.info.facadeFile"
						:disabled="model1.info.processStatus==0"
						:del-icon="!model1.info.processStatus==0"
						sizeType="['compressed']"
						@select="(e) => select(e, 'facade')"
						return-type="object">
					</uni-file-picker>
				</view>
				<view class="held">

				</view>
				<u-form-item :required='true' label="商铺内景照" prop="info.internalUrls" :borderBottom='false' ref="item1">
				</u-form-item>
				<view class="imgBox">
					<uni-file-picker 
						v-model="model1.info.internalFile"
						:disabled="model1.info.processStatus==0"
						:del-icon="!model1.info.processStatus==0"
						sizeType="['compressed']"
						limit="3"
						multiple
						@select="(e) => select(e, 'internal')"
						@delete="delIMG">
					</uni-file-picker>
				</view>
				<view class="held">

				</view>
				<view class="press">
					<view v-if="model1.info.processStatus==1">审核通过</view>
					<view v-if="model1.info.processStatus==2">审核失败</view>
					<view v-if="model1.info.processStatus==0">审核中</view>
					<view>
						{{model1.info.processOpinion || ''}}
					</view>

				</view>
			</u--form>
			<button class="subit" @click="submit"
				:disabled="model1.info.processStatus==1||model1.info.processStatus==0">
				提交
			</button>
		</view>
		<u-picker :show="show" ref="uPicker" :columns="columns" @confirm="confirm" @cancel="show=false"
			@change="changeHandler" :defaultIndex="defaultIndex"></u-picker>
	</view>
</template>

<script>
	import {
		customerApply,
		businessApply,
		areaTree,
		applyMerchantsType
	} from "@/api/wine/wine.js"
	import {
		uploadXpPath
	} from "@/api/merchants/merchants.js"
	import {
		businessGet
	} from "@/api/work/work.js"
	export default {
		data() {
			return {
				show: false,
        		imageValue:[],
				columns: [],
				origiData: [], //获取到的原始数据
				value: "", //
				defaultIndex: [],
				countNmae: '', //选中用来展示的数据
				merId: '', //商户id
				businessId: '', //业务员id
				radiolist1: [{
						name: '是',
						value: true,
					},
					{
						name: '否',
						value: false,
					},
				],
				model1: {
					info: {
						storeName: '',
						comName: '',
						name: '',
						phone: '',
						storeAddress: '',
						creditCode: '',
						county: '',
						// deskNum: '',
						isOutsideProvince: false,
						businessLicenseUrl: '',
						facadeUrl: '',
						internalUrls: [],
						businessLicenseFile: [],
						facadeFile: [],
						internalFile: [],
					},
				},
				rules: {
					'info.storeName': {
						type: 'string',
						required: true,
						message: '请填写店铺名称',
						trigger: ['blur', 'change']
					},
					'info.comName': {
						type: 'string',
						required: true,
						message: '请填写公司名称',
						trigger: ['blur', 'change']
					},
					'info.name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'info.phone': {
						required: true,
						message: '请填写电话',
						trigger: ['blur', 'change']
					},
					'info.storeAddress': {
						type: 'string',
						required: true,
						message: '请填写地址',
						trigger: ['blur', 'change']
					},
					'info.creditCode': {
						type: 'string',
						required: true,
						message: '请填写社会信用代码',
						trigger: ['blur', 'change']
					},
					// 'info.deskNum': {
					// 	type: 'number',
					// 	required: true,
					// 	message: '请填写桌数or输入数字',
					// 	trigger: ['blur', 'change']
					// },
					'info.businessLicenseUrl': {
						type: 'string',
						required: true,
						message: '请选择营业执照',
						trigger: ['blur', 'change']
					},
					'info.facadeUrl': {
						type: 'string',
						required: true,
						message: '请选择门牌照',
						trigger: ['blur', 'change']
					},
					'info.internalUrls': {
						type: 'array',
						required: true,
						message: '请选择至少一张内景照',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		onShow() {
			// console.log(this.model1.info)
		},
		onLoad(e) {
			this.getArea()
			this.getUserInfo()
			if (e.id) {
				this.merId = e.id
			}
			if (e.scene) {
				let codeString = unescape(e.scene)
				let obj={}
				codeString.split('&').forEach(pair => {
				    let [key, value] = pair.split('=');
				    obj[key] = value;
				});
				this.businessId = obj.businessId
				console.log('yewuy',this.businessId)
			}
			this.getMerInfo(this.merId ? this.merId : this.$store.getters.id)
			// console.log(e,e.id,this.merId)
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			// 上传成功
			async select(e, type) {
				uni.showLoading({
					title:'上传中',
					mask:true
				})
				switch(type) {
				case 'business':
					this.model1.info.businessLicenseUrl = await this.uploadIamge({filePath: e.tempFilePaths[0]})
					this.model1.info.businessLicenseFile = this.convertUrlToFileObj(this.model1.info.businessLicenseUrl)
					break;
				case 'facade':
					this.model1.info.facadeUrl = await this.uploadIamge({filePath: e.tempFilePaths[0]})
					this.model1.info.facadeFile = this.convertUrlToFileObj(this.model1.info.facadeUrl)
					break;
				case 'internal':
					const filePath =  await this.uploadIamge({filePath: e.tempFilePaths[0]})
					if(this.model1.info.internalUrls==null){
						this.model1.info.internalUrls=[]
					}
					this.model1.info.internalUrls.push(filePath);
					this.model1.info.internalFile = this.convertUrlToFileObj(this.model1.info.internalUrls)
					break;
				}
				uni.hideLoading()
			},
			uploadIamge(param){
				return new Promise((resolve,reject) => {
					uploadXpPath(param).then(response => {
						resolve(response.data);
					});
				})
			},
			//图片删除
			delIMG(e){
				const num = this.model1.info.internalUrls.findIndex(v => v === e.tempFilePath);
				this.model1.info.internalUrls.splice(num, 1);
			},
			//获取用户信息
			getUserInfo() {
				this.$store.dispatch('GetInfo').then(res => {
					// console.log('111') 
				})
			},
			//判断是否申请过了
			getMerInfo(e) {
				let that = this
				uni.showLoading({
					title: '加载中',
				})
				businessGet(e).then(response => {
					uni.hideLoading()
					console.log(response)
					if (response.data) {
						that.model1.info = response.data
						// 转换数据格式用于回显
						that.model1.info.businessLicenseFile = that.convertUrlToFileObj(response.data.businessLicenseUrl)
						that.model1.info.facadeFile = that.convertUrlToFileObj(response.data.facadeUrl)
						that.model1.info.internalFile = that.convertUrlToFileObj(response.data.internalUrls)
						that.countNmae = response.data.countyName
					}else{
						
					}
					// console.log(that.model1.info)
				})
			},
			change() {
				this.show = true;
			},
			//初始化开始数据
			handelData() {
				//默认贵州省、贵阳市、南明区
				let shi_s = '520100';
				let qu_s = '520102';

				let shi = [];
				let qu = [];
				this.origiData.forEach((shi_item, shi_index) => {
					if (shi_item.id == shi_s) {
						this.defaultIndex[0] = shi_index
						shi_item.children.forEach((qu_item, qu_index) => {
							if (qu_item.id == qu_s) {
								this.defaultIndex[1] = qu_index
							}
							qu.push(qu_item.name);
						})
					}
					shi.push(shi_item.name);
				});
				this.columns.push(
					JSON.parse(JSON.stringify(shi)),
					JSON.parse(JSON.stringify(qu))
				);
				console.log('初始', this.columns)
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					this.origiData.forEach(item => {
						if (value[0] == item.name) {
							let qu = [];
							let flag = item.children[0].name;
							item.children.forEach((val, ol) => {
								qu.push(val.name);
							});
							picker.setColumnValues(1, qu);
						}
					});
				}
			},
			// 确认选中的数据
			confirm(e) {
				let shi = this.origiData[e.indexs[0]]
				let qu = shi.children[e.indexs[1]]
				this.model1.info.county = qu.id
				this.countNmae = "贵州省" + " " + e.value[0] + " " + e.value[1]
				this.show = false;
			},
			groupChange(n) {
				this.model1.info.isOutsideProvince = n
			},
			submit() {
				let that = this
				that.$refs.uForm.validate().then(res => {
					// uni.$u.toast('校验通过')
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					if (that.merId) {
						let data2 = {
							name: that.model1.info.name,
							phone: that.model1.info.phone,
							storeName: that.model1.info.storeName,
							comName: that.model1.info.comName,
							// deskNum: that.model1.info.deskNum,
							creditCode: that.model1.info.creditCode,
							county: that.model1.info.county,
							storeAddress: that.model1.info.storeAddress,
							businessLicenseUrl: that.model1.info.businessLicenseUrl,
							facadeUrl: that.model1.info.facadeUrl,
							internalUrls: that.model1.info.internalUrls,
							isOutsideProvince: that.model1.info.isOutsideProvince,
							id: that.merId,
							businessId: that.$store.getters.id
						}
						// console.log('发起申请，业务员，传了id',data2)
						businessApply(data2).then(response => {
							// console.log('发起申请，业务员，传了id',response)
							if (response.data) {
								uni.hideLoading()
								uni.$u.toast('提交成功')
								//参数传递成功，清空表单
								that.model1.info = {
									storeName: '',
									comName: '',
									name: '',
									phone: '',
									storeAddress: '',
									creditCode: '',
									county: '',
									// deskNum: '',
									isOutsideProvince: false,
									businessLicenseUrl: '',
									facadeUrl: '',
									internalUrls: '',
								}
								setTimeout(() => {
									that.$tab.switchTab("/pages/index")
								}, 1000)
							}
						})
					} else {
						let data = {
							name: that.model1.info.name,
							phone: that.model1.info.phone,
							storeName: that.model1.info.storeName,
							comName: that.model1.info.comName,
							// deskNum: that.model1.info.deskNum,
							creditCode: that.model1.info.creditCode,
							county: that.model1.info.county,
							storeAddress: that.model1.info.storeAddress,
							businessLicenseUrl: that.model1.info.businessLicenseUrl,
							facadeUrl: that.model1.info.facadeUrl,
							internalUrls: that.model1.info.internalUrls,
							isOutsideProvince: that.model1.info.isOutsideProvince,
							businessId: that.businessId
						}
						customerApply(data).then(response => {
							console.log('发起申请，没有传id', response)
							if (response.data) {
								uni.hideLoading()
								uni.$u.toast('提交成功')
								//参数传递成功，清空表单
								that.model1.info = {
									storeName: '',
									comName: '',
									name: '',
									phone: '',
									storeAddress: '',
									creditCode: '',
									county: '',
									// deskNum: '',
									isOutsideProvince: false,
									businessLicenseUrl: '',
									facadeUrl: '',
									internalUrls: '',
								}
								setTimeout(() => {
									that.$tab.switchTab("/pages/index")
								}, 1000)
							}
						})
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
					console.log(errors)
				})
			},
			//获得区县数据
			getArea() {
				let that = this
				uni.showLoading({
					title: '加载中',
				})
				areaTree().then(response => {
					uni.hideLoading()
					that.origiData = response.data
					that.handelData();
				})
			},
			// 处理URL转换为文件对象
			convertUrlToFileObj(url) {
				if(!url) return [];
				if(Array.isArray(url)) {
					return url.map(item => {
						const name = item.split('/').pop();
						const extname = name.split('.').pop();
						return {
							name,
							extname,
							url: item
						};
					});
				}
				const name = url.split('/').pop();
				const extname = name.split('.').pop();
				return [{
					name,
					extname,
					url
				}];
			},
		}
	}
</script>

<style>
	page {
		background-color: white;
	}

	.box {
		width: 690rpx;
		height: fit-content;
		margin: 20rpx auto;
		padding-bottom: 100rpx;
	}

	.boxTitle {
		width: 690rpx;
		height: 50rpx;
		line-height: 50rpx;
		font-size: 32rpx;
		color: #999999;
	}

	.imgBox {
		width: 690rpx;
		padding-bottom: 20rpx;
		height: fit-content;
		display: flex;
		flex-wrap: wrap;
	}

	.busImg {
		width: 300rpx;
		height: 200rpx;
	}

	.busImg1 {
		width: 400rpx;
		height: 300rpx;
	}

	.held {
		width: 100%;
		height: 2rpx;
		background-color: #F1F1F1;
	}

	.subit {
		width: 690rpx;
		height: 70rpx;
		text-align: center;
		line-height: 70rpx;
		font-size: 32rpx;
		color: #FFFFFF;
		border-radius: 50rpx;
		background-color: #E84E22;
		margin-top: 30rpx;
	}

	.radioBox {
		width: 200rpx;
		height: 100%;
		margin-left: 250rpx;
	}

	.countBox1 {
		width: 100%;
		height: 100%;
		color: #999999;
	}

	.countBox2 {
		width: 100%;
		height: 100%;
	}

	.press {
		width: 690rpx;
		/* height: 80rpx; */
		/* line-height: 80rpx; */
		color: #E84E22;
		font-size: 28rpx;
		margin: 10rpx auto;
		border-bottom: 2rpx solid #999999;
	}
</style>